package com.clip.action;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.jml.Email;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.clip.action.util.SessionAttributeKey;
import com.clip.entity.SystemDate;
import com.clip.entity.User;
import com.clip.entity.UserDate;
import com.clip.entity.UserEmail;
import com.clip.entity.Usermobileinfo;
import com.clip.service.SystemDateService;
import com.clip.service.UserDateService;
import com.clip.service.UserEmailService;
import com.clip.service.UserService;
import com.clip.service.UsermobileinfoService;
import com.clip.util.Struts2Utils;
import com.clip.util.ToolsUtils;
import com.opensymphony.xwork2.ActionSupport;

@Controller
@Scope("prototype")
public class ControlAction extends ActionSupport{

	private static final long serialVersionUID = 3300414284140534805L;
	
	@Autowired
	private UserService userService;
	@Autowired
	private UserEmailService userEmailService;
	@Autowired 
	private UserDateService userDateService;
	@Autowired 
	private SystemDateService systemDateService;
	@Autowired 
	private UsermobileinfoService usermobileinfoService;
	
	private String nameInput;
	private String sexInput;
	private String birthInput;
	private long birthlong;
	private int sex;
	private String qqInput;
	private String msnInput;
	private String mobileInput;
	private String livingInput;
	private String jobInput;
	private String eduInput;
	private String blogInput;
		
	private String emailInput;
	private String descInput;
	private String status;
	
	private int emailid;
	private int emailaccept;
	public void getSystemHoliday(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String year = request.getParameter("year");
		year=(year==null||year=="") ? String.valueOf(Calendar.getInstance().get(Calendar.YEAR)) : year;
		Map<String,Object> infoMap=new LinkedHashMap<String,Object>();
		if(year.matches("^[0-9]+$")){
			List<SystemDate> list = systemDateService.getSystemHoliday(Integer.valueOf(year));
			infoMap=systemDateService.orgSystemHolidayList(list);
		}
		Struts2Utils.renderText(ToolsUtils.getJSON(infoMap));
	}
	
	public void getTodayDate(){
		Map<String,Object> infoMap=new LinkedHashMap<String,Object>();
		Calendar today = Calendar.getInstance();
		infoMap.put("year", today.get(Calendar.YEAR));
		infoMap.put("month", today.get(Calendar.MONTH));
		infoMap.put("day", today.get(Calendar.DAY_OF_MONTH));
		Struts2Utils.renderText(ToolsUtils.getJSON(infoMap));
	}
	
	public void getHoliday(){
		HttpServletRequest request = ServletActionContext.getRequest();
		User user = (User) request.getSession().getAttribute(SessionAttributeKey.USER);
		String year = request.getParameter("year");
		year=(year==null||year=="") ? String.valueOf(Calendar.getInstance().get(Calendar.YEAR)) : year;
		Map<String,Object> infoMap=new LinkedHashMap<String,Object>();
		if(year.matches("^[0-9]+$")){

			List<UserDate> list= userDateService.getHoliday(user, Integer.valueOf(year));
			infoMap =userDateService.orgHolidayList(list);
			
		}
		Struts2Utils.renderText(ToolsUtils.getJSON(infoMap));
	}
	/**
	 * 自定义节假日
	 */
	public void setHoliday(){
		String result="{result:'保存成功',flag:0}";
		HttpServletRequest request = ServletActionContext.getRequest();
		boolean Illegal=false;
		String year = request.getParameter("year");
		String holidays = request.getParameter("holidays");
		String regEx="^([1-2]\\d{3})[\\-](0?[0-9]|10|11)[\\-]([1-2]?[0-9]|0[1-9]|30|31)[\\-]([A-Za-z0-9\u4e00-\u9fa5]{1,})[\\-](0|1)";
		String[] holiday = holidays.split("\\|");
		for(String str : holiday){
			if(!str.matches(regEx)){
				Illegal=true;
			}
		}
		if(holidays.equals("nothing")){
			holiday = new String[0];
			Illegal = false;
		}
		if((!Illegal&&year.matches("^[0-9]+$"))){
			User user = (User) request.getSession().getAttribute(SessionAttributeKey.USER);
			userDateService.saveHoliday(user, Integer.valueOf(year), holiday);
		}
		Struts2Utils.renderText(result);
	}
	
	//绑定新邮箱
	public void saveEmail(){
		HttpSession session=Struts2Utils.getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		UserEmail userEmail=userEmailService.saveUserEmail(this.emailInput,currentUser);
		JSONObject jsonObject=new JSONObject();
		if(userEmail==null){
			jsonObject.put("result", 0);
			jsonObject.put("errormsg", "添加的邮箱已被占用");
		}else{
			jsonObject.put("result", 1);
			jsonObject.put("emailid", userEmail.getId());
		}
		Struts2Utils.renderJson(jsonObject.toString());
	}
	//验证绑定邮箱
	public void activite(){
		String result="此链接无效";
		if(ToolsUtils.searchEmpty(status).size()<=0){
			result=userEmailService.activite(status);
		}
		HttpSession session=Struts2Utils.getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		String url=null;
		if(currentUser!=null){
			url=(String) session.getAttribute(SessionAttributeKey.VISITURL);
		}else{
			url=ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT);
		}
		String js="<script>alert('"+result+"');window.location.href='"+url+"';</script>";
		Struts2Utils.renderHtml(js);
	}
	//删除绑定邮箱
	public void deleteEmail(){
		HttpSession session=Struts2Utils.getSession();
		User currentUser = (User) session.getAttribute(SessionAttributeKey.USER);
		this.userEmailService.deleteEmail(emailid, currentUser);
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("result", 1);
		Struts2Utils.renderJson(jsonObject.toString());
	}
	//绑定邮箱并发送邮件
	public void bindEmail(){
		String result="{result:'添加失败'}";
		if(ToolsUtils.searchEmpty(emailInput,descInput).size()<=0&&emailInput.matches("^[a-z0-9_\\.]+@([a-z0-9][a-z0-9]+\\.){1,4}[a-z]{2,3}")){
			HttpSession session=ServletActionContext.getRequest().getSession();
			User user = (User) session.getAttribute(SessionAttributeKey.USER);
			UserEmail userEmail = new UserEmail(user.getId(),emailInput,0,0,ToolsUtils.htmlEnCode(descInput),0);
			result=userEmailService.bindUserEmail(user,userEmail,true);
		}
		Struts2Utils.renderText(result);
	}
	//重新发送验证邮件
	public void resendEmail(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User currentUser = (User) session.getAttribute(SessionAttributeKey.USER);
		String result=userEmailService.resendEmail(currentUser,this.emailid);
		JSONObject jsonObject=new JSONObject();
		if(result==null){
			jsonObject.put("result", 1);
			if(currentUser.getUsertype()==2){
				session.setAttribute(SessionAttributeKey.VISITURL, ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/control/ccinfo.html");
			}else{
				session.setAttribute(SessionAttributeKey.VISITURL, ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/control/userinfo.html");
			}
		}else{
			jsonObject.put("result", 0);
			jsonObject.put("errormsg",result);
		}
		Struts2Utils.renderJson(jsonObject.toString());
	}
	public void resendCCInfoEmail(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User currentUser = (User) session.getAttribute(SessionAttributeKey.USER);
		JSONObject jsonObject=new JSONObject();
		if(Email.parseStr(emailInput)!=null){
			String result=userEmailService.resendCCInfoEmail(currentUser,emailInput);
			if(result==null){
				jsonObject.put("result", 1);
			}else{
				jsonObject.put("result", 0);
				jsonObject.put("errormsg", result);
			}
		}else{
			jsonObject.put("result", 0);
			jsonObject.put("errormsg", "请输入正确的邮件地址");
			
		}
		Struts2Utils.renderJson(jsonObject.toString());
	}
	
	//获得用户所有邮箱（已绑定和未验证）
	public void userEmail(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User user = (User) session.getAttribute(SessionAttributeKey.USER);
		Map<String,Object> emailMap = userEmailService.getUserEmail(user.getId());
		Struts2Utils.renderXml(ToolsUtils.getDOM(emailMap));
	}
	//获得用户详细信息
	public void userInfo(){
		JSONObject jsonObject=new JSONObject();
		User currentUser=(User) Struts2Utils.getSession().getAttribute(SessionAttributeKey.USER);
		if(currentUser!=null){
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			Usermobileinfo mobileinfo=usermobileinfoService.getBindableMobile(currentUser.getId());
			jsonObject.put("result",1);
			jsonObject.put("email",currentUser.getEmail());
			jsonObject.put("name", currentUser.getName());
			jsonObject.put("birth", currentUser.getBirth()==null?"":formatter.format(new Date(currentUser.getBirth())));
			jsonObject.put("birthlong", currentUser.getBirth()==null?0l:currentUser.getBirth());
			jsonObject.put("qq",currentUser.getQq()==null?"":currentUser.getQq());
			jsonObject.put("msn",currentUser.getMsn()==null?"":currentUser.getMsn());
			jsonObject.put("blog",currentUser.getBlog()==null?"":currentUser.getBlog());
			jsonObject.put("sex",currentUser.getSex());
			if(mobileinfo!=null){
				jsonObject.put("mobilenum", mobileinfo.getMobilenum());
				jsonObject.put("mobileisbindable", mobileinfo.getStatus());
			}else{
				jsonObject.put("mobilenum", "");
			}
			jsonObject.put("issina", currentUser.getPwd().equals("sina"));
			jsonObject.put("isouter", currentUser.getIsouter());
			String address=currentUser.getLiving();
			if(address==null||address.length()<=0){
				jsonObject.put("address", "");
				jsonObject.put("sufaddress", "");
				jsonObject.put("addresscode", "");
			}else{
				if(address.indexOf(":")>0){
					String []addarr=address.split(":");
					String preaddress=addarr[0];
					String sufaddress=addarr[1];
					if(preaddress.indexOf("_")>0){
						String[]areaarr=preaddress.split("_");
						int pid=Integer.parseInt(areaarr[0]);
						String padd=UserService.getRealAddress("Province",pid);
						int cid=Integer.parseInt(areaarr[1]);
						String cadd=null;
						String dadd=null;
						if(cid==0){
							cadd="";
						}else{
							cadd=UserService.getRealAddress("City",cid);
						}
						if(areaarr.length==3){
							int did=Integer.parseInt(areaarr[2]);
							if(did==0){
								dadd="";
							}else{
								dadd=UserService.getRealAddress("District", did);
							}
						}else{
							dadd="";
						}
						jsonObject.put("address", padd+cadd+dadd+" "+sufaddress);
						jsonObject.put("sufaddress", sufaddress);
						jsonObject.put("addresscode", preaddress);
					}else{
						int pid=Integer.parseInt(preaddress);
						String padd=UserService.getRealAddress("Province",pid);
						if(padd==null){
							jsonObject.put("address", sufaddress);
							jsonObject.put("sufaddress", sufaddress);
							jsonObject.put("addresscode", "");
						}else{
							jsonObject.put("address", padd+" "+sufaddress);
							jsonObject.put("sufaddress", sufaddress);
							jsonObject.put("addresscode", preaddress);
						}
					}
					
				}else{
					jsonObject.put("address", address);
					jsonObject.put("sufaddress", address);
					jsonObject.put("addresscode", "");
				}
			}
		}else{
			jsonObject.put("result", 0);
			jsonObject.put("errormsg", "当前用户不存在");
		}
		Struts2Utils.renderJson(jsonObject.toString());
	}
	//修改用户详细信息
	public void saveUserInfo(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		JSONObject jsonObject=new JSONObject();
		if(!currentUser.getName().equals(this.nameInput)){
			boolean isexist=this.userService.checkIsExistName(currentUser.getName());
			if(isexist){
				jsonObject.put("result", 0);
				jsonObject.put("errormsg", "用户姓名已经存在");
			}
		}
		currentUser.setName(nameInput);
		currentUser.setQq(qqInput);
		currentUser.setMsn(msnInput);
		currentUser.setBirth(birthlong);
		currentUser.setLiving(livingInput);
		currentUser.setBlog(blogInput);
		currentUser.setSex(sex);
		
		currentUser = userService.updateUser(currentUser);
		if(currentUser!=null){
			session.setAttribute(SessionAttributeKey.USER, currentUser);
			jsonObject.put("result", 1);
		}
		Struts2Utils.renderJson(jsonObject.toString());
	}
	
	public void updateAvatar(){
		HttpServletRequest request=ToolsUtils.getRequest();
		String imgDada=request.getParameter("imgContent");
		String userID=request.getParameter("userID");
		String xml=ToolsUtils.getDOM(userService.updateAvatar(userID,imgDada));
		userService.checkUserLogo(false,request.getSession());
		Struts2Utils.renderText(xml);
	}
	public void getUpdateAvatorInfo(){
		HttpSession session=Struts2Utils.getSession();
		User currentUser=(User) session.getAttribute(SessionAttributeKey.USER);
		Map returnmap=new HashMap();
		returnmap.put("userID", currentUser.getId());
		returnmap.put("url", ToolsUtils.getWebHeadUrl(null,ToolsUtils.WEBHEADURLPORT)+"/control/controlAjax!updateAvatar.action");
		HashMap<String, String> apu=ToolsUtils.getApachePhysicalURL();
		String path="";
		path=apu.get("apacheAvatarPath");
		List list=this.userService.getUserLogoByUid(currentUser.getId());
		returnmap.put("bigpic",list.get(0));
		returnmap.put("smallpic",list.get(1));
		Struts2Utils.renderText(ToolsUtils.getDOM(returnmap));
	}
	
	public void updateUserEmail(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		User currentUser = (User) session.getAttribute(SessionAttributeKey.USER);
		JSONObject jsonObject=new JSONObject();
		String result=this.userEmailService.updateUserEmail(currentUser,this.emailid,this.emailaccept);
		if(result==null){
			jsonObject.put("result",1);
		}else{
			jsonObject.put("result",0);
			jsonObject.put("errormsg", result);
		}
		Struts2Utils.renderJson(jsonObject.toString());
	}
	
	public void updateCCEmail(){
		JSONObject jsonObject=new JSONObject();
		if(emailInput!=null&&Email.parseStr(emailInput)!=null){
			HttpSession session=ServletActionContext.getRequest().getSession();
			User currentUser = (User) session.getAttribute(SessionAttributeKey.USER);
			String result=userEmailService.updateCCEmail(currentUser,emailInput);
			if(result==null){
				jsonObject.put("result",1);
			}else{
				jsonObject.put("result",0);
				jsonObject.put("errormsg", result);
			}
			
		}else{
			jsonObject.put("result", 0);
			jsonObject.put("errormsg", "请输入正确的邮件地址");
		}
		Struts2Utils.renderJson(jsonObject.toString());
	}
	
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getNameInput() {
		return nameInput;
	}

	public void setNameInput(String nameInput) {
		this.nameInput = nameInput;
	}

	public String getSexInput() {
		return sexInput;
	}

	public void setSexInput(String sexInput) {
		this.sexInput = sexInput;
	}

	public String getBirthInput() {
		return birthInput;
	}

	public void setBirthInput(String birthInput) {
		this.birthInput = birthInput;
	}

	public String getQqInput() {
		return qqInput;
	}

	public void setQqInput(String qqInput) {
		this.qqInput = qqInput;
	}

	public String getMsnInput() {
		return msnInput;
	}

	public void setMsnInput(String msnInput) {
		this.msnInput = msnInput;
	}

	public String getMobileInput() {
		return mobileInput;
	}

	public void setMobileInput(String mobileInput) {
		this.mobileInput = mobileInput;
	}
	public String getEmailInput() {
		return emailInput;
	}
	public void setEmailInput(String emailInput) {
		this.emailInput = emailInput;
	}
	public String getDescInput() {
		return descInput;
	}
	public void setDescInput(String descInput) {
		this.descInput = descInput;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}

	public String getLivingInput() {
		return livingInput;
	}

	public void setLivingInput(String livingInput) {
		this.livingInput = livingInput;
	}

	public String getJobInput() {
		return jobInput;
	}

	public void setJobInput(String jobInput) {
		this.jobInput = jobInput;
	}

	public String getEduInput() {
		return eduInput;
	}

	public void setEduInput(String eduInput) {
		this.eduInput = eduInput;
	}

	public String getBlogInput() {
		return blogInput;
	}

	public void setBlogInput(String blogInput) {
		this.blogInput = blogInput;
	}

	public long getBirthlong() {
		return birthlong;
	}

	public void setBirthlong(long birthlong) {
		this.birthlong = birthlong;
	}

	public int getSex() {
		return sex;
	}

	public void setSex(int sex) {
		this.sex = sex;
	}

	public int getEmailid() {
		return emailid;
	}

	public void setEmailid(int emailid) {
		this.emailid = emailid;
	}

	public int getEmailaccept() {
		return emailaccept;
	}

	public void setEmailaccept(int emailaccept) {
		this.emailaccept = emailaccept;
	}
	
}
